package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.BookRatingDTO;
import com.sky.entity.Books;
import com.sky.entity.UserBookRatings;
import com.sky.entity.Users;
import com.sky.exception.BaseException;
import com.sky.mapper.BooksMapper;
import com.sky.mapper.UserBookRatingsMapper;
import com.sky.mapper.UsersMapper;
import com.sky.service.UserbookratingsService;
import com.sky.vo.BookRatingVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.mybatis.mp.core.mybatis.mapper.context.Pager;
import cn.mybatis.mp.core.sql.executor.chain.QueryChain;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author majun
 * @package com.sky.service.impl
 * @date 2025/1/2 20:20
 */
@Service
@Slf4j
public class UserbookratingsServiceImpl implements UserbookratingsService {

    @Autowired
    private UserBookRatingsMapper userBookRatingsMapper;
    
    @Autowired
    private BooksMapper booksMapper;
    
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 添加评分和评论
     */
    @Override
    @Transactional
    public void addRating(BookRatingDTO bookRatingDTO) {
        // 获取当前登录用户ID
        Integer userId = BaseContext.getCurrentId().intValue();
        
        // 检查图书是否存在
        Books book = booksMapper.get(where -> where.eq(Books::getBookId, bookRatingDTO.getBookId()));
        if (book == null) {
            throw new BaseException(MessageConstant.BOOK_NOT_FOUND);
        }
        
        // 检查用户是否已经评价过该图书
        UserBookRatings existingRating = userBookRatingsMapper.get(where -> 
            where.eq(UserBookRatings::getUserId, userId)
                .eq(UserBookRatings::getBookId, bookRatingDTO.getBookId())
        );
        
        if (existingRating != null) {
            throw new BaseException(MessageConstant.RATING_ALREADY_EXISTS);
        }
        
        // 验证评论长度
        if (bookRatingDTO.getComment() != null && bookRatingDTO.getComment().length() > 500) {
            throw new BaseException(MessageConstant.COMMENT_TOO_LONG);
        }
        
        // 创建新的评分记录
        UserBookRatings userBookRatings = new UserBookRatings();
        BeanUtils.copyProperties(bookRatingDTO, userBookRatings);
        userBookRatings.setUserId(userId);
        userBookRatings.setCreateTime(LocalDateTime.now());
        userBookRatings.setUpdateTime(LocalDateTime.now());
        userBookRatings.setStatus(1);
        
        // 保存评分
        userBookRatingsMapper.save(userBookRatings);
    }

    /**
     * 修改评分和评论
     */
    @Override
    @Transactional
    public void updateRating(BookRatingDTO bookRatingDTO) {
        Integer userId = BaseContext.getCurrentId().intValue();
        
        // 检查评分是否存在且属于当前用户
        UserBookRatings rating = userBookRatingsMapper.get(where -> 
            where.eq(UserBookRatings::getRatingId, bookRatingDTO.getRatingId())
                .eq(UserBookRatings::getUserId, userId)
        );
        
        if (rating == null) {
            throw new BaseException(MessageConstant.RATING_NOT_FOUND);
        }
        
        // 验证评论长度
        if (bookRatingDTO.getComment() != null && bookRatingDTO.getComment().length() > 500) {
            throw new BaseException(MessageConstant.COMMENT_TOO_LONG);
        }
        
        // 更新评分信息
        rating.setRating(bookRatingDTO.getRating());
        rating.setComment(bookRatingDTO.getComment());
        rating.setUpdateTime(LocalDateTime.now());
        
        userBookRatingsMapper.update(rating);
    }

    /**
     * 删除评分和评论
     */
    @Override
    @Transactional
    public void deleteRating(Integer ratingId) {
        Integer userId = BaseContext.getCurrentId().intValue();
        
        // 检查评分是否存在且属于当前用户
        UserBookRatings rating = userBookRatingsMapper.get(where -> 
            where.eq(UserBookRatings::getRatingId, ratingId)
                .eq(UserBookRatings::getUserId, userId)
        );
        
        if (rating == null) {
            throw new BaseException(MessageConstant.RATING_DELETE_FAILED);
        }
        
        // 逻辑删除
        rating.setStatus(0);
        userBookRatingsMapper.update(rating);
    }

    /**
     * 获取指定图书的所有评分和评论（分页）
     */
    @Override
    public Pager<BookRatingVO> getBookRatings(Integer bookId, Integer page, Integer pageSize) {
        // 创建分页对象
        Pager<UserBookRatings> pager = Pager.of(page, pageSize);
        
        // 查询评分数据（分页）
        pager = QueryChain.of(userBookRatingsMapper)
                .eq(UserBookRatings::getBookId, bookId)
                .eq(UserBookRatings::getStatus, 1)
                .orderByDesc(UserBookRatings::getCreateTime)
                .paging(pager);
        
        // 转换为VO对象
        List<BookRatingVO> voList = pager.getResults().stream().map(rating -> {
            BookRatingVO vo = new BookRatingVO();
            BeanUtils.copyProperties(rating, vo);
            
            // 获取用户信息
            Users user = usersMapper.get(where -> where.eq(Users::getUserId, rating.getUserId()));
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 创建返回的分页对象
        Pager<BookRatingVO> resultPager = new Pager<>();
        resultPager.setResults(voList);
        resultPager.setTotal(pager.getTotal());
        resultPager.setNumber(pager.getNumber());
        resultPager.setSize(pager.getSize());
        
        return resultPager;
    }

    /**
     * 获取用户的所有评分和评论（分页）
     */
    @Override
    public Pager<BookRatingVO> getUserRatings(Integer userId, Integer page, Integer pageSize) {
        // 创建分页对象
        Pager<UserBookRatings> pager = Pager.of(page, pageSize);
        
        // 查询评分数据（分页）
        pager = QueryChain.of(userBookRatingsMapper)
                .eq(UserBookRatings::getUserId, userId)
                .eq(UserBookRatings::getStatus, 1)
                .orderByDesc(UserBookRatings::getCreateTime)
                .paging(pager);
        
        // 转换为VO对象
        List<BookRatingVO> voList = pager.getResults().stream().map(rating -> {
            BookRatingVO vo = new BookRatingVO();
            BeanUtils.copyProperties(rating, vo);
            
            // 获取用户信息
            Users user = usersMapper.get(where -> where.eq(Users::getUserId, rating.getUserId()));
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 创建返回的分页对象
        Pager<BookRatingVO> resultPager = new Pager<>();
        resultPager.setResults(voList);
        resultPager.setTotal(pager.getTotal());
        resultPager.setNumber(pager.getNumber());
        resultPager.setSize(pager.getSize());
        
        return resultPager;
    }

    /**
     * 获取指定图书的平均评分
     */
    @Override
    public Double getAverageRating(Integer bookId) {
        List<UserBookRatings> ratings = userBookRatingsMapper.list(where -> 
            where.eq(UserBookRatings::getBookId, bookId)
                .eq(UserBookRatings::getStatus, 1)
        );
        
        if (ratings.isEmpty()) {
            return 0.0;
        }
        
        double sum = ratings.stream()
                .mapToInt(UserBookRatings::getRating)
                .sum();
                
        return sum / ratings.size();
    }
}
